# -*- conding:UTF-8 -*-

'''
@ Project: P7_lx1
@ File: user_view.py
@ Author: 罗婷
@ Date：2022/6/8 19:11

'''
import json
import random

import redis
from flask import Blueprint, jsonify
from flask_restful import Api, Resource, reqparse
from werkzeug.security import generate_password_hash

from common.celery.tasks import sendSmsCode
from common.utils.jwtToken_generate_check import generate_token

from models.user import *

user_bp = Blueprint('user_bp', __name__, url_prefix='/v1_0')
api = Api(user_bp)

# 注册
class Register(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        argss = ['username', 'password', 'nickname', 'mobile', 'comfirmpassword']
        for i in argss:
            parser.add_argument(i)
        args = parser.parse_args()
        account = args['username']
        password = args['password']
        uname = args['nickname']
        mobile = args['mobile']
        ag_password = args['comfirmpassword']
        if len(account) > 32:
            return jsonify(msg='账号太长', code=400)
        if not all([account, password, uname, mobile, ag_password]):
            return jsonify(msg='信息不完整', code=400)
        if password != ag_password:
            return jsonify(msg='两次密码输入不一致', code=400)
        pwd_hash = generate_password_hash(password)
        try:
            user = UserModel(uname=uname, password=pwd_hash, account=account, mobile=mobile)
            db.session.add(user)
            db.session.commit()
            return jsonify(msg='注册成功', code=200)
        except Exception as e:
            print(e)
            return jsonify(msg='添加用户操作失败', code=500)


# 发送短信验证码  配置容联云 celery异步 生成 发送
class SendSmsCode(Resource):

    def post(self):
        smsCode = f'{random.randint(100000, 999999)}'
        print('生成的短信验证码是====={', smsCode)
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        args = parser.parse_args()
        mobile = args['mobile']
        print('前端传来的手机号', mobile)
        #
        ret = sendSmsCode.delay(mobile, smsCode)
        if ret:   # 发送成功  存入redis
            rds = redis.Redis(db=2)
            key = f'mobile:{mobile}:smsCode'
            rds.set(key, smsCode, ex=2*60*60)
            rds.close()
            return jsonify(msg='手机号发送成功, 注意查收', code=200)
        else:
            return jsonify(msg='手机号发送失败', code=500)


# 登录 手机号 验证码 mobile sms
#         token: res.data.token,
#         id: res.data.user_id,
#         refresh_token: res.refresh_token  //刷新生成的

class LoginView(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('code')
        args = parser.parse_args()
        mobile = args['mobile']
        sms = args['code']

        if not all(['mobile', 'sms']):
            return jsonify(smg='数据不完整', code=400)

        rds = redis.Redis(db=2)
        key = f'mobile:{mobile}:smsCode'
        smsCode = rds.get(key)
        rds.close()
        print('取出的验证码转化后json.loads(smsCode)', smsCode.decode())
        print('前端传来的验证码', sms)
        if not smsCode:
            return jsonify(sms='验证码已过期', code=400)
        if smsCode.decode() == sms:
            try:
                user = UserModel.query.filter_by(mobile=mobile).first()
            except:
                return jsonify(msg='用户未注册', code=400)

            # 生成token
            payload = {'user_id': user.uid, 'user': user.account}
            token = generate_token(payload)

            # data = {'token': token, 'user_id': user.uid}
            return jsonify(msg='登录成功', code=200, token=token)

        else:
            return jsonify(sms='验证码错误', code=400)


# 展示所有频道
# class ChannelsAll(Resource):
#     def get(self):
#         ...







# 注册
api.add_resource(Register, '/register')
# 发送短信验证码
api.add_resource(SendSmsCode, '/sms_code')
# 登录
api.add_resource(LoginView, '/authorizations')
# api.add_resource(ChannelsAll, '/channels')